//
//  CreateAccountViewController.m
//  jungoo
//
//  Created by Sinbad Fly on 8/14/12.
//  Copyright (c) 2012 ABOM. All rights reserved.
//

#import "CreateAccountViewController.h"
#import "UniversityViewController.h"
#import "Extensions.h"
#import "HomeViewController.h"
#import "AppDelegate.h"
#import "User.h"
#import "CreateAccountMoreController.h"

#define kCATag 100


@implementation CreateAccountViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
}

#pragma mark - Private Method

- (BOOL)validToCreateAccountWithFull:(BOOL)bFullValid
{    
    if ([[cellUI1 fieldTextWithTag:kCATag].text length] == 0 && bFullValid) {
        [JGoUtility showAlert:@"Please enter your name."];
        return NO;
    }
    else {
        [[JGoUtility sharedCreateAccount] setValue:[cellUI1 fieldTextWithTag:kCATag].text forKey:@"name"];
    }
    
    if ([[cellUI2 fieldTextWithTag:kCATag].text length] == 0 && bFullValid) {
        [JGoUtility showAlert:@"Please enter your surname."];
        return NO;
    }
    else {
        [[JGoUtility sharedCreateAccount] setValue:[cellUI2 fieldTextWithTag:kCATag].text forKey:@"surname"];
    }    
    
    if ([[cellUI3 titleTextWithTag:kCATag].text length] == 0 && bFullValid) {
        [JGoUtility showAlert:@"Please enter your university."];
        return NO;
    }
    else {
        [[JGoUtility sharedCreateAccount] setValue:[cellUI3 titleTextWithTag:kCATag].text forKey:@"university"];
    }    
    
    if ([[cellUI4 fieldTextWithTag:kCATag].text length] == 0 && bFullValid) {
        [JGoUtility showAlert:@"Please enter your email."];
        return NO;
    }
    else {        
        NSString *emailString = [cellUI4 fieldTextWithTag:kCATag].text;
        
        if ([JGoUtility validateEmail:emailString] || !bFullValid) {
            [[JGoUtility sharedCreateAccount] setValue:[cellUI4 fieldTextWithTag:kCATag].text forKey:@"email"];
        }
        else {
            [JGoUtility showAlert:@"You entered which is not a true email."];
            return NO;
        }
    }      
    
    if ([[cellUI5 titleTextWithTag:kCATag].text length] == 0 && bFullValid) {
        [JGoUtility showAlert:@"Please enter a password."];
        return NO;
    }
    else {
        [[JGoUtility sharedCreateAccount] setValue:[cellUI5 titleTextWithTag:kCATag].text forKey:@"password"];
    }    
    
    if ([[cellUI6 titleTextWithTag:kCATag].text length] == 0 && bFullValid) {
        [JGoUtility showAlert:@"Please enter confirm password."];
        return NO;
    }
    else {
        [[JGoUtility sharedCreateAccount] setValue:[cellUI6 titleTextWithTag:kCATag].text forKey:@"repassword"];
    }    
    
    if (!([[cellUI5 titleTextWithTag:kCATag].text isEqualToString:[cellUI6 titleTextWithTag:kCATag].text])) {
        
        if (bFullValid) {
            [JGoUtility showAlert:@"Re-password entered which is not match."];
            return NO;        
        }
    }
    
    return YES;
}

#pragma mark - View lifecycle

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self.tableView reloadData];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setBackButtonImageActiveName:nil 
                          inactiveName:@"btn_home" 
                                target:self 
                                action:@selector(back:)];
    
    [self setTitle:@"Create Account"];
    [self.tableView setBackgroundView:[[[UIImageView alloc] 
                                        initWithImage:[UIImage imageNamed:@"home_bg.png"]] autorelease]];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return NO;
}

- (void)dealloc
{
    [cellUI1 release];
    [cellUI2 release];
    [cellUI3 release];
    [cellUI4 release];
    [cellUI5 release];
    [cellUI6 release];
    [cellUI7 release];    
    
    [super dealloc];
}

#pragma mark - Action

- (void)back:(id)sender
{
    [[JGoUtility sharedCreateAccount] setValue:nil forKey:@"university"];
    [self.navigationController dismissModalViewControllerAnimated:YES];
}

- (IBAction)createAccount:(id)sender
{
/*
    CreateAccountMoreController * camVC = [[[CreateAccountMoreController alloc] initWithNibName:@"CreateAccountMoreController"
                                                                                         bundle:nil] autorelease];
    
    [self.navigationController pushViewController:camVC animated:YES];
*/
    
    if ([self validToCreateAccountWithFull:YES]) {
        [JGoUtility showProgressInView:self.view 
                                target:self 
                                 title:@"Create your account..." 
                              selector:@selector(delayCreateAccount:)];
    }        
}

#pragma mark - TableView Deletate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1) {
        return 100;
    }
    
    return 44;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return (section == 0 ? 6 : 1);
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    
    switch (indexPath.section) {
        case 0: {
            
            switch (indexPath.row) {
                case 0: {     
                    cell = cellUI1;
                    break;
                }
                case 1: {  
                    cell = cellUI2;
                    break;
                }
                case 2: {    
                    cell = cellUI3;
                    UILabel *universityLabel = (id)[cell viewWithTag:100];
                    universityLabel.text = [[JGoUtility sharedCreateAccount] objectForKey:@"university"];
                    break;
                }                    
                case 3: {
                    cell = cellUI4;
                    break;
                }                    
                case 4: {         
                    cell = cellUI5;
                    break;
                }                    
                case 5: {    
                    cell = cellUI6;
                    break;
                }                                        
            }
            
            break;
        }
            
        case 1: {
            cell = cellUI7;
            cell.backgroundView = [[[UIView alloc] initWithFrame:CGRectZero] autorelease];
            cell.backgroundView.backgroundColor = [UIColor clearColor];
            cell.backgroundColor = [UIColor clearColor];
            break;
        }
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section == 0 && indexPath.row == 2) {
    
        UniversityViewController * uVC = [[[UniversityViewController alloc] initWithNibName:@"UniversityViewController"
                                                                                     bundle:nil] autorelease];
            
        [self.navigationController pushViewController:uVC animated:YES];
    }
}

#pragma mark - TextField Delegeate

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    UITableViewCell *cell = (id)textField.superview.superview;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    
    [self.tableView setContentInset:UIEdgeInsetsMake(0, 0, 218, 0)];
    [self.tableView scrollToRowAtIndexPath:indexPath 
                          atScrollPosition:UITableViewScrollPositionNone 
                                  animated:YES];
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    [self.tableView setContentInset:UIEdgeInsetsMake(0, 0, 0, 0)];
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] 
                          atScrollPosition:UITableViewScrollPositionNone 
                                  animated:YES];
    return YES;
}

#pragma mark - Delay Method

- (void)delayCreateAccount:(MBProgressHUD*)progress
{
    NSError *error = nil;                 
    
    
    [JGoAPI registerAccountWithName:[[JGoUtility sharedCreateAccount] objectForKey:@"name"]  
                           surname:[[JGoUtility sharedCreateAccount] objectForKey:@"surname"]                              
                              email:[[JGoUtility sharedCreateAccount] objectForKey:@"email"] 
                           password:[[JGoUtility sharedCreateAccount] objectForKey:@"password"]  
                         university:[[JGoUtility sharedCreateAccount] objectForKey:@"university"]
                                lat:[JGoUtility sharedLatitude] 
                                lon:[JGoUtility sharedLongitude] 
                              error:&error];
    
    if (error) {
        [JGoUtility showAlert:[error localizedDescription]];
    }
    else {
        
        error = nil;
        NSDictionary *userInfor = nil;
        
        userInfor = [JGoAPI loginWithEmail:[[JGoUtility sharedCreateAccount] objectForKey:@"email"]
                               andPassword:[[JGoUtility sharedCreateAccount] objectForKey:@"password"] 
                                     error:&error];
        
        if (error) {
            [JGoUtility showAlert:[error localizedDescription]];
        }
        else {
            
            [[JGoUtility sharedCreateAccount] setValue:[userInfor objectForKey:@"user_id"] forKey:@"user_id"];

                          
            [[NSUserDefaults standardUserDefaults] setValue:[[JGoUtility sharedCreateAccount] 
                                                             objectForKey:@"email"] forKey:@"user"];
            [[NSUserDefaults standardUserDefaults] setValue:[[JGoUtility sharedCreateAccount] 
                                                             objectForKey:@"password"] forKey:@"password"];
            [[NSUserDefaults standardUserDefaults] synchronize];             
        }
         
        NSLog(@"%@",[JGoUtility sharedCreateAccount]);
        CreateAccountMoreController * camVC = [[[CreateAccountMoreController alloc] initWithNibName:@"CreateAccountMoreController"
                                                                                             bundle:nil] autorelease];
        
        [self.navigationController pushViewController:camVC animated:YES];
    }
    
    [progress hide:YES];
}

@end
